package com.xgl.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.xgl.pojo.*;
import com.xgl.service.IDepartmentService;
import com.xgl.service.IGradeService;
import com.xgl.service.IMajorService;
import com.xgl.service.INationService;
import com.xgl.utils.Md5Utils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 学生参加活动信息 前端控制器
 * </p>
 *
 * @author 最最帅气的熊国林
 * @since 2021-05-26
 */
@RestController
@RequestMapping("/student/grade")
public class GradeController {
    @Autowired
    private IGradeService iGradeService;
    @Autowired
    private IDepartmentService iDepartmentService;
    @Autowired
    private IMajorService iMajorService;
    @Autowired
    private INationService iNationService;

    @ApiOperation(value = "生成学生成绩信息hash")
    @GetMapping("compute/{id}")
    public RespBean computeHash(@PathVariable Integer id) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        List<Grade> list = iGradeService.getGradeInfo(id);
        Map<String,String> map = new HashMap<String,String>();
        list.forEach(gardeInfo -> {
            map.put("id",gardeInfo.getId().toString());
            map.put("s_number",gardeInfo.getS_number().toString());
            map.put("name",gardeInfo.getName().toString());
            map.put("nationId",gardeInfo.getNationId().toString());
            map.put("sex",gardeInfo.getSex().toString());
            map.put("grade",gardeInfo.getGrade().toString());
            map.put("majorId",gardeInfo.getMajorId().toString());
            map.put("departmentId",gardeInfo.getDepartmentId().toString());
            map.put("s_level",gardeInfo.getS_level().toString());
            map.put("s_category",gardeInfo.getS_category().toString());
            map.put("s_test",gardeInfo.getS_test().toString());
            map.put("test_time",gardeInfo.getTest_time().toString());
            map.put("s_garde",gardeInfo.getS_garde().toString());
            map.put("test_place",gardeInfo.getTest_place().toString());

        });
        String hashCode = Md5Utils.SHA256(
                map.get("id")+ map.get("s_number")
                        + map.get("name")+ map.get("nationId")
                        + map.get("grade") + map.get("sex")
                        + map.get("majorId") + map.get("departmentId")
                        + map.get("s_level") + map.get("s_category")
                        + map.get("s_test") + map.get("test_time")
                        + map.get("s_garde") + map.get("test_place")
        );
        System.out.println(hashCode);

        return iGradeService.insertHashCode(id,hashCode);
    }

    @ApiOperation(value = "获取所有学生成绩信息（分页）")
    @GetMapping("/")
    public RespPageBean getGradeByPage(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "10") Integer size,
                                       Grade grade, LocalDate[] beginDateScope) {
        return iGradeService.getGradeByPage(currentPage, size, grade, beginDateScope);
    }

    @ApiOperation(value = "增加学生成绩信息")
    @PostMapping("/")
    public RespBean addGrade(@RequestBody Grade grade){
        return iGradeService.addGrade(grade);
    }

    @ApiOperation(value = "更新学生成绩信息")
    @PutMapping("/")
    public RespBean updateGrade(@RequestBody Grade grade){
        if (iGradeService.updateById(grade)){
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    @ApiOperation(value = "删除学生成绩信息")
    @DeleteMapping("/{id}")
    public RespBean deleteGrade(@PathVariable Integer id){
        if (iGradeService.removeById(id)){
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation(value = "获取所有民族")
    @GetMapping("/nation")
    public List<Nation> getAllNation(){
        return iNationService.list();
    }

    @ApiOperation(value = "获取所有专业")
    @GetMapping("/major")
    public List<Major> getAllPosition(){
        return iMajorService.list();
    }

    @ApiOperation(value = "获取所有学院")
    @GetMapping("/department")
    public List<Department> getAllDepartment(){
        return iDepartmentService.list();
    }

    @ApiOperation(value = "导出学生获奖数据")
    @GetMapping(value = "/export",produces = "application/octet-stream")
    public void exportGradeinfo(HttpServletResponse response){
        List<Grade> list = iGradeService.getGradeInfo(null);
        ExportParams params = new ExportParams("学生成绩信息表","学生成绩信息表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params,Grade.class,list);
        //输出
        ServletOutputStream outputStream = null;
        try {
            //流形式
            response.setHeader("content-type","application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("学生成绩信息表.xls","UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (null != outputStream){
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导入学生成绩数据")
    @ApiImplicitParams({@ApiImplicitParam(name="file",value = "上传文件",dataType = "MultipartFile")})
    @PostMapping("/import")
    public RespBean importGradeinfo(MultipartFile file){
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(1);
        List<Nation> nations = iNationService.list();
        List<Major> majors = iMajorService.list();
        List<Department> departments = iDepartmentService.list();
        try {
            List<Grade> list = ExcelImportUtil.importExcel(file.getInputStream(), Grade.class, params);
            list.forEach(gradeinfo ->{
                //民族id
                gradeinfo.setNationId(nations.get(nations.indexOf(new Nation(gradeinfo.getNation().getName()))).getId());
                //专业id
                gradeinfo.setMajorId(majors.get(majors.indexOf(new Major(gradeinfo.getMajor().getName()))).getId());
                //学院id
                gradeinfo.setDepartmentId(departments.get(departments.indexOf(new Department(gradeinfo.getDepartment().getName()))).getId());
                //职称id

            });
            if (iGradeService.saveBatch(list)){
                return RespBean.success("导入成功");
            }
            return RespBean.error("导入失败");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败");
    }

}
